package com.alongstudio.account.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alongstudio.account.commons.exception.BusinessException;
import com.alongstudio.account.commons.utils.BeanUtil;
import com.alongstudio.account.constants.SystemConstant;
import com.alongstudio.account.dao.ICategoryDao;
import com.alongstudio.account.entity.Category;
import com.alongstudio.account.service.ICategoryService;
import com.alongstudio.account.vo.CategoryVo;

@Service("CategoryService")
public class CategoryService extends BaseService implements ICategoryService {

	private String className = CategoryService.class.getName();
	@Autowired
	private ICategoryDao categoryDao;
	
	@Override
	public Map getSubCategoryMapForSettings(String userId) throws BusinessException {
		Map result = new HashMap();
		List<Category> firstClass = categoryDao.getFirstClassCategory(userId, SystemConstant.CATEGORY_TYPE_EXPENDITURE);
		
		if(firstClass != null){
			for(Category c : firstClass){
				
			}
		}
		return result;
	}

	@Override
	public List<CategoryVo> getFirstClassCategory(String userId, String type) throws BusinessException {
		List<CategoryVo> list = new ArrayList<CategoryVo>();
//		try {
			List<Category> result = categoryDao.getFirstClassCategory(userId, type);
			if(result != null && !result.isEmpty()){
				for(Category cat : result){
					CategoryVo vo = new CategoryVo();
					BeanUtil.copyProperties(cat, vo, true);
					if(cat.getParent()!= null){
						vo.setParentId(cat.getParent().getId());
					}
					list.add(vo);
				}
			}
//		}
//		catch (Exception e) {
//			throw new BusinessException(className, e);
//		}
		return list;
	}

	@Override
	public List<CategoryVo> getSubCategoryByParentId(String parentId) throws BusinessException {
		List<CategoryVo> list = null;
//		try {
//			// List param = new ArrayList();
//			// param.add(parentId);
//			list = dao.query("from Category c where c.parent.id=" + parentId + " order by c.sortNum");
//		}
//		catch (Exception e) {
//			throw new BusinessException(className, e);
//		}
		return list;
	}

	@Override
	public String createCategory(CategoryVo vo) throws BusinessException {
		try {
			Category cate = new Category();
			BeanUtil.copyProperties(vo, cate, true);
			Integer maxSortNum = categoryDao.queryMaxSortNum(vo);
			
			if(maxSortNum == null){
				maxSortNum = SystemConstant.SORT_NUM_INIT;
			}else{
				maxSortNum++;
			}
			vo.setSortNum(maxSortNum);
			String parentId = vo.getParentId();
			boolean hasParent = parentId != null && !parentId.isEmpty();
			Category parent = (Category) categoryDao.queryByPk(Category.class, parentId);
			if(parent.getHasChild().equals(SystemConstant.HAS_CHILD_NO)){
				parent.setHasChild(SystemConstant.HAS_CHILD_YES);
				categoryDao.update(parent);
			}
			cate.setParent(parent);
			String treeCode = hasParent ? parent.getTreeCode() + "." + maxSortNum : String.valueOf(maxSortNum);
			cate.setTreeCode(treeCode);
			dao.create(cate);
			return vo.getId();
		}
		catch (Exception e) {
			throw new BusinessException(className, e);
		}
	}

	@Override
	public boolean updateCategory(CategoryVo cate) throws BusinessException {
		try {
			dao.update(cate);
			return true;
		}
		catch (Exception e) {
			throw new BusinessException(className, e);
		}
	}

	@Override
	public boolean deleteCategory(String id) throws BusinessException {
		boolean result = false;
		try {
			Category cate = (Category) dao.queryByPk(Category.class, id);
			if (cate != null) {
				//如果有父节点，必须查看父节点是否还有其他子节点，再决定是否设置父节点的hasChild
				Category parent = cate.getParent();
				if(parent != null){
					String parentTreeCode = parent.getTreeCode();
//					List<Category> childList = dao.query("from Category c where c.parent.treeCode='"+parentTreeCode+"'");
//					if(childList != null){
//						if(childList.size() == 1){
//							Category temp = childList.get(0);
//							if(temp.getId().equals(cate.getId())){
//								parent.setHasChild(SystemConstant.HAS_CHILD_NO);
//								dao.update(parent);
//							}
//						}
//					}
				}
				
				// 如果没有子节点
				// TODO 删除前要查看是否被其他数据关联。如果关联则返回false
				if (cate.getHasChild().equals(SystemConstant.HAS_CHILD_NO)) {
					dao.deleteByPk(Category.class, id);
				}
				else {
					String treeCode = cate.getTreeCode();
					String hql = "from Category c where c.treeCode like '" + treeCode + "%'";
//					List<Category> list = dao.query(hql);
//					dao.deleteII(list);
				}
				result = true;
				
			}
		}
		catch (Exception e) {
			throw new BusinessException(className, e);
		}
		return result;
	}

	@Override
	public List<CategoryVo> findSameClassCategoryBySubId(String subId) throws BusinessException {
		List<CategoryVo> result=null;
		try{
			Category subCate = (Category)dao.queryByPk(Category.class, subId);
			Category parent = subCate.getParent();
			if(parent != null){
				String treeCode = parent.getTreeCode();
				Integer grade = parent.getGrade();
				grade++;
				String hql = "from Category c where c.treeCode like '"+treeCode+"%' and c.grade="+grade;
//				result = dao.query(hql);
			}
			
		}catch (Exception e) {
			throw new BusinessException(className, e);
		}
		return result;
	}


}
